package top.fzqblog.music.activity;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;
import top.fzqblog.firstapp.R;
import top.fzqblog.model.MusicList;
import top.fzqblog.model.Song;
import top.fzqblog.music.adapter.SongListAdapter;
import top.fzqblog.music.event.PlayEvent;
import top.fzqblog.music.util.MusicUtils;
import top.fzqblog.service.SongService;

import static top.fzqblog.utils.Constants.TAG;

/**
 * Created by 抽离 on 2017/10/25 0025.
 */

public class MusicSearch extends AppCompatActivity {

    SongService songService = new SongService();

    private SearchView searchView;

    private AutoCompleteTextView searchEditText;

    @BindView(R.id.searchRoot)
    public LinearLayout searchRoot;

    @BindView(R.id.toolbar)
    public Toolbar toolbar;

    @BindView(R.id.musicListContainer)
    public RecyclerView recyclerView;

    int width;

    int height;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_search);
        ButterKnife.bind(this);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        height = wm.getDefaultDisplay().getHeight();
        Log.i(TAG, "widht: " + width + "height:" + height);
        // 让根布局进行动画
        searchRoot.post(new Runnable() {
            @Override
            public void run() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Animator animator = createRevealAnimator(false, 0  , 0);
                    animator.start();
                }
            }
        });

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    // 动画
    private Animator createRevealAnimator(boolean reversed, int x, int y) {
        float hypot = (float) Math.hypot(width, height);
        float startRadius = reversed ? hypot : 0;
        float endRadius = reversed ? 0 : hypot;

        Animator animator = ViewAnimationUtils.createCircularReveal(
                searchRoot, x, y,
                startRadius,
                endRadius);
        animator.setDuration(800);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        return animator;
    }

    private void initSearchViewListener(){
        // 监听搜索框文字变化
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                //当用户提交查询的时候会调用
                Log.i(TAG, "onQueryTextSubmit: " + query);
                return false; //返回false，SearchView会处理一些操作，反之SearchView不会做任何处理
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.i(TAG, "onQueryTextChange: " + newText);

                songService.getMusicList(new Subscriber<MusicList>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable throwable) {
                    }

                    @Override
                    public void onNext(MusicList musicList) {
                        List<top.fzqblog.model.List> list = musicList.getList();
                        Log.i(TAG, "list: " + list);
                        SongListAdapter songListAdapter = new SongListAdapter(R.layout.music_item, list);
                        songListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                                songService.getSong(new Subscriber<Song>() {//通过rid获取具体歌曲
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable throwable) {
                                        Toast.makeText(MusicSearch.this, "该首歌不能播放，请换一首", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onNext(Song song) {
                                        top.fzqblog.music.model.Song localSong = MusicUtils.convertNetToLocal(song);//将网络图片转成本地图片
                                        ArrayList<top.fzqblog.music.model.Song> songs = new ArrayList<>();
                                        songs.add(localSong);
                                        EventBus.getDefault().post(new PlayEvent(localSong, songs, 0, PlayEvent.PlayAction.PLAY));
                                        Log.i(TAG, "song: " + song);
                                    }
                                }, list.get(i).getRid());
                            }
                        });
                        recyclerView.setAdapter(songListAdapter);
                        recyclerView.setLayoutManager(new LinearLayoutManager(MusicSearch.this));
                    }
                }, newText);
                return false;
            }
        });
    }

    /**
     * 返回按钮
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (!TextUtils.isEmpty(searchEditText.getText())) {
                    try {
                        //如果搜索框中有文字，则会先清空文字，但网易云音乐是在点击返回键时直接关闭搜索框
                        searchEditText.setText("");
                        Method method = searchEditText.getClass().getDeclaredMethod("onCloseClicked");
                        method.setAccessible(true);
                        method.invoke(searchEditText);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    finish();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
}

    @SuppressLint("RestrictedApi")
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_music_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.menu_search);

        //通过MenuItem得到SearchView
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchEditText = searchView.findViewById(R.id.search_src_text);

        //设置搜索框直接展开显示。左侧有放大镜(在搜索框中) 右侧有叉叉 可以关闭搜索框
//       searchView.setIconified(false);
        //设置搜索框直接展开显示。左侧有放大镜(在搜索框外) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
//        searchView.setIconifiedByDefault(false);
        //设置搜索框直接展开显示。左侧无放大镜(在搜索框中) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
        searchView.onActionViewExpanded();

        //改变serchView hint的颜色,字体颜色
        searchEditText.setTextColor(getResources().getColor(R.color.colorWhite));
        searchEditText.setHintTextColor(getResources().getColor(R.color.colorWhite));
        searchEditText.setTextSize(14);
        searchView.setQueryHint("搜索歌曲");
//        SearchManager searchManager = (SearchManager)getSystemService(SEARCH_SERVICE);
//        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//修改搜索框控件间的间隔（这样只是为了在细节上更加接近网易云音乐的搜索框）
        searchEditText.setThreshold(1);
        LinearLayout search_edit_frame = searchView.findViewById(R.id.search_edit_frame);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) search_edit_frame.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        search_edit_frame.setLayoutParams(params);
        initSearchViewListener();
        return super.onCreateOptionsMenu(menu);
    }


}
